package db

/***
文档地址：
http://www.topgoer.cn/docs/gorm/gormlianjieshujuku
*/

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"sync"
	"time"
)

var db *gorm.DB
var err_db error

type DbConn struct {
}

var instance *DbConn
var once sync.Once

func GetInstance() *DbConn {
	once.Do(func() {
		instance = &DbConn{}
	})
	return instance
}

func (m *DbConn) InitDB(DbUser, DbPwd, DbHost, DbName string) (issucc bool) {

	dburl := DbUser + ":" + DbPwd + "@tcp(" + DbHost + ")/" + DbName + "?charset=utf8&parseTime=true"
	fmt.Println("init log logdatabase:", dburl)
	db, err_db = gorm.Open("mysql", dburl)
	db.DB().SetConnMaxLifetime(100 * time.Second) //最大连接周期，超过时间的连接就close
	db.DB().SetMaxOpenConns(100)                  //设置最大连接数
	db.DB().SetMaxIdleConns(0)                    //设置闲置连接数
	db.SingularTable(true)
	db.LogMode(true)
	//设置全局表名禁用复数
	//指定表前缀，修改默认表名
	gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
		return "tbl_" + defaultTableName
	}
	if err_db != nil {
		fmt.Println("连接数据库出错:", err_db)
		return false
	}
	return true
}

/*
* @fuc  对外获取数据库连接对象db
 */
func (m *DbConn) GetDB() (db_con *gorm.DB) {
	return db
}

//查看对应记录是否存在
func IsExit(db *gorm.DB, class interface{}) (bool, error) {
	err := db.Find(class).Error
	if err != nil {
		return false, err
	}
	return true, nil
}
